package com.tgy.leetcode;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Stack;

/**
 *
 * https://leetcode-cn.com/problems/clumsy-factorial/
 */
public class _1006_笨阶乘 {

    public static int clumsy(int N) {

        if (N == 1) {
            return 1;
        }

        /**
         * * / +  -
         */
        int index = 0;
        int val = N - 1;
        Deque<Integer> stack = new LinkedList<>();
        Deque<String> optStack = new LinkedList<>();
        stack.addLast(N);
        while (val > 0) {

            int tmp = index % 4;
            switch (tmp) {
                case 0:

                    stack.addLast(stack.removeLast() * val);
                    break;
                case 1:
                    stack.addLast(stack.removeLast() / val);
                    break;
                case 2:
                    stack.addLast(val);
                    optStack.addLast("+");
                    break;
                case 3:
                    stack.addLast(val);
                    optStack.addLast("-");
                    break;
                default:
            }

            index++;
            val--;
        }

        while (!optStack.isEmpty()) {

            String opt = optStack.removeFirst();
            int one = stack.removeFirst();
            int two = stack.removeFirst();

            if ("+".equals(opt)) {

                stack.addFirst(one + two);
            }else if ("-".equals(opt)) {
                stack.addFirst(one - two);
            }
        }

        return stack.removeFirst();
    }

    public static void main(String[] args) {

        /**
         * 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1
         * 11 + 7 - 7+ 3 - 2
         * 11 + 7 - 7 + 1
         *
         */
        System.out.println(clumsy(4));
    }
}
